package com.kehutong.user.service.impl;

import com.kehutong.common.DoveClient;
import com.kehutong.contact.entity.Resident;
import com.kehutong.contact.enums.BindType;
import com.kehutong.contact.service.impl.ResidentServiceImpl;
import com.kehutong.user.dao.AssetsUserDao;
import com.kehutong.user.service.AssetsUserService;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONArray;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.webservice.WebService;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.jdbc.Page;
import org.coraframework.orm.jdbc.execute.Condition;
import org.coraframework.orm.jdbc.execute.PageCondition;
import org.coraframework.orm.jdbc.execute.QueryCondition;
import org.coraframework.util.Objects;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 资产用户
 * @author: liukunlong
 * @date: 2021-08-04 19:08
 */
@WebService("/crm/assets/user/service")
public class AssetsUserServiceImpl implements AssetsUserService {
    private static final Logger logger= LoggerFactory.getLogger(AssetsUserServiceImpl.class);
    @Inject
    private AssetsUserDao assetsUserDao;

    @Inject
    private JdbcSession jdbcSession;

    @Inject
    private DoveClient doveClient;

    @Inject
    private ResidentServiceImpl residentService;


    /**
     * 根据条件获取用户项目分页列表
     *
     * @param jsonObject 查询对象
     * @return 项目分页对象
     * @throws IOException 操作异常
     */
    @ReqMapping("/user/community/page")
    public Page<Map<String, Object>> userCommunityPage(JSONObject jsonObject) throws Exception {
        List<String> bindTypeList = new ArrayList<>();
        bindTypeList.add(BindType.NO_BIND.getId());
        bindTypeList.add(BindType.BIND.getId());
        PageCondition query = Condition.createPage(false);
        query.eq(jsonObject,"residentNo");
        query.in("bindType", bindTypeList);
        query.order("createTime", "desc");
        query.groupBy("communityNo");
        query.groupBy("communityName");
        query.groupBy("residentNo");
        Page<Map<String, Object>> page = assetsUserDao.loadUserCommunityPage(query);
       /* List<Map<String, Object>> list = page.getList();
        if (Objects.nonEmpty(list)) {
            for(Map<String, Object> v:list){
                String residentNo = String.valueOf(v.get("id"));

            }
        }*/
        return page;
    }
    /**
     * 根据条件获取标签列表
     *
     * @param jsonObject 查询对象
     * @return 标签列表
     * @throws IOException 操作异常
     */
    @ReqMapping("/user/page")
    public Page<Map<String, Object>> assetsUserPage(JSONObject jsonObject) throws Exception {
        PageCondition query = Condition.createPage(false);
        String search = jsonObject.getString("search");
        if (Objects.nonEmpty(search)) {
            query.markBegin();
            query.like("a.id", search).or();
            query.like("a.realname", search).or();
            query.like("a.mobile", search).or();
            query.markEnd();
        }
        //多个编号查询
        JSONArray ids=jsonObject.getJSONArray("id");
        if(Objects.nonEmpty(ids)){
            query.in("a.id",ids);
        }

        //多个小区编号查询
        JSONArray communityNos=jsonObject.getJSONArray("communityNos");
        if(Objects.nonEmpty(communityNos)){
            query.in("b.communityNo",communityNos);
        }
        query.eq(jsonObject,"b.buildNo","b.houseNo","a.firstLetter");
        query.order("a.createTime", "desc");
        query.page(jsonObject);

        // 根据以上条件查询房屋的分页数据
        Page<Map<String, Object>> page = assetsUserDao.loadPage(query);
        List<Map<String, Object>> list = page.getList();
        if (Objects.nonEmpty(list)) {
            for(Map<String, Object> v:list){
                String residentNo = String.valueOf(v.get("id"));
                v.put("tagNames",getUserTag(residentNo));
            }
        }
        return page;
    }


    /**
     * 获取用户
     *
     * @param userNo
     * @return
     * @throws Exception
     */
    private List<String> getUserTag(String userNo) throws Exception {
        List<String> result=new ArrayList<>();
        Map<String, String> mapping = new HashMap<>();
        JSONObject tagResult = doveClient.post("/crm/user/tag/service/user/tag/list", (http) -> {
            JSONObject body = new JSONObject();
            body.put("userNo", userNo);
            http.setBody(body.toJSONString());
        });
        JSONArray tagNameList=tagResult.getJSONArray("data");
        if(Objects.nonEmpty(tagNameList)){
            for (Object tagNameObj : tagNameList) {
                JSONObject tagName = (JSONObject) tagNameObj;
                result.add(tagName.getString("name"));
            }
        }
        return result;
    }

    @ReqMapping("/count")
    public Map<String,Object> getUserCommunityCount(JSONObject jsonObject) throws Exception{
        QueryCondition query = Condition.createQuery(false);
        query.eq("deleted", false);
        query.order("createTime","desc");
        query.eq(jsonObject,"residentNo");
        Map<String,Object> resultMap=assetsUserDao.getUserCommunityCount(query);
        //设置住户是否启用
        String residentNo=jsonObject.getString("residentNo");
        Resident resident=residentService.getResidentById(residentNo);
        if(Objects.isNull(resident)){
            logger.error("账户标志为{}的账户没有匹配到住户信息",residentNo);
            resultMap.put("enable",false);
        }else{
            resultMap.put("enable",resident.isEnable());
        }
        return resultMap;
    }

    /**
     * 获取用户跟进人
     *
     * @param jsonObject 查询对象
     * @return 用户及跟进人信息
     * @throws IOException 操作异常
     */
    @ReqMapping("/user/follow")
    public Map<String, Object> getUserFollow(JSONObject jsonObject) throws Exception{
        Map<String, Object> resultMap=new HashMap<>();
        String id=jsonObject.getString("id");
        Resident resident=residentService.getResidentById(id);
        if(Objects.isNull(resident)){
            throw new RuntimeException("住户信息不存在");
        }
        resultMap.put("id",resident.getId());
        resultMap.put("avatar",resident.getAvatar());
        resultMap.put("nickname", resident.getNickname());
        resultMap.put("realname",resident.getRealname());
        resultMap.put("mobile",resident.getMobile());
        JSONObject result = doveClient.post("/kht-bin/wwout/get/message/context", (http) -> {
            JSONObject body = new JSONObject();
            body.put("id", resident.getId());
            body.put("userIds",resident.getUsers());
            http.setBody(body.toJSONString());
        });
        if (result.getIntValue("code") == 200) {
            JSONObject data=result.getJSONObject("data");
            resultMap.put("customerExternalUserid", data.getString("customerUserId"));
            resultMap.put("employeeUserId", data.getJSONArray("employeeUserId"));
        }
        return resultMap;
    }
}
